#include "ThreadPool.h"


namespace loong
{
WorkThread::WorkThread(ThreadPool *pool)
{
    m_pool = pool;
}

WorkThread::~WorkThread()
{
}

void WorkThread::run()
{
    if (m_initCallback!=nullptr)
    {
        m_initCallback();
    }
    
    if (m_workCallback == nullptr)
    {
        printf("Please set thread work function.");
        return;
    }

    while (true)
    {
        m_workCallback();
    }
}

void WorkThread::setInitCallback(function<void ()> initCallback)
{
    m_initCallback = initCallback;
}

void WorkThread::setWorkCallback(function<void ()> workCallback)
{
    m_workCallback = workCallback;
}


////////////////////////////////////////////////////////////////////////////
ThreadPool::ThreadPool(uint32_t threadNum)
:m_threadNum(threadNum),m_works(threadNum),m_threads(threadNum)
{
}

ThreadPool::~ThreadPool()
{
    for (auto itw=m_works.begin(); itw!=m_works.end(); itw++)
    {
        delete *itw;
    }
    
    for (auto itt=m_threads.begin(); itt!=m_threads.end(); itt++)
    {
        delete *itt;
    }
}

void ThreadPool::setThreadInitCallback(function<void ()> threadInitCallback)
{
    m_threadInitCallback=threadInitCallback;
}
void ThreadPool::setThreadWrokCallback(function<void ()> threadWorkCallback)
{
    m_threadWorkCallback=threadWorkCallback;
}

void ThreadPool::start()
{
    for (uint32_t i = 0; i < m_threadNum; i++)
    {
        WorkThread *work = new WorkThread(this);
        
        work->setInitCallback(m_threadInitCallback);
        work->setWorkCallback(m_threadWorkCallback);
        
        m_works[i] = work;
        m_threads[i] = new std::thread(&WorkThread::run, work);
        m_threads[i]->detach();
    }
}
}


